"use strict";
import './style.scss'
class Controller {
    constructor (systemService, $state, $stateParams, $location, uiNotification) {
        "ngInject"
        this.notify           = uiNotification;
        this.stateParam       = $stateParams;
        this.location         = $location;
        this.type             = $state.current.name.match(/post|user/)[ 0 ];
        this.stateParam.tab   = this.type
        // 权限菜单操作
        this.addMenuList      = [];
        this.delMenuList      = [];
        this.checkedGrantList = [];
        // 权限组件操作
        this.addCompList      = [];
        this.delCompList      = [];
        this.checkedCompList  = [];
        this.current          = {
            page    : $stateParams.orgName,
            type    : this.type == "post" ? "岗位" : "用户",
            typeName: $stateParams.curCheck
        };
        this.treeData         = {
            parMenuId   : 0,
            grantObjType: $state.current.data.grantType,
            grantObjId  : $stateParams.core,
            sysCode     : $stateParams.sysCode
        }

        this.compData = {
            grantObjType: $state.current.data.grantType,
            sysCode     : this.sysCode,
            grantObjId  : $stateParams.core,
            menuId      : ""
        }

        this.privMenuAddData = {
            grantObjType: $state.current.data.grantType,
            operType    : 'ADD',
            grantObjId  : $stateParams.core
        };

        this.privMenuDelData = {};

        this.privCompAddData = {
            grantObjType: $state.current.data.grantType,
            operType    : 'ADD',
            grantObjId  : $stateParams.core
        };

        this.privCompDelData = {};

        this.service = systemService;

        this.getTree()

    }

    getTree () {
        this.service.getTree('menuTree', this.treeData).then((res) => {
            this.treeNode = res.data;
            for (let i = 0, l = res.data.length; i < l; i++) {
                if ( res.data[ i ].hadPriv ) {
                    this.checkedGrantList.push({
                        privId     : res.data[ i ].privId,
                        privGrantId: res.data[ i ].privGrantId
                    });
                }
            }
            this.initMenu = angular.copy(this.checkedGrantList);
            this.isLoad   = true;
        })
    }

    toggleCheck (type, node) {
        __DEBUG__ && console.log(node)
        if ( type == 'menu' ) {
            let ifMenuChecked = (node.hadPriv = !node.hadPriv);
            let ifMenuExist = _.findIndex(this.checkedGrantList, {privId: node.privId});
            let ifInitMenu  = _.findIndex(this.initMenu, {privId: node.privId});
            __DEBUG__ && console.log(this.initMenu)
            __DEBUG__ && console.log(ifMenuChecked)
            __DEBUG__ && console.log(ifMenuExist)
            __DEBUG__ && console.log(ifInitMenu)
            if ( ifMenuChecked ) {
                if ( ifMenuExist > -1 ) {
                    let delIdx = _.findIndex(this.delMenuList, {
                        privGrantId: node.privGrantId
                    });
                    this.delMenuList.splice(delIdx, 1);
                }
                if ( ifMenuExist == -1 ) {
                    let addIdx = _.findIndex(this.addMenuList, {
                        privId: node.privId
                    });
                    if ( addIdx == -1 ) {
                        this.addMenuList.push({
                            privId  : node.privId,
                            menuName: node.menuName
                        })
                        this.checkedGrantList.push({
                            privId     : node.privId,
                            privGrantId: ""
                        })
                    }
                }

            } else {

                if ( ifInitMenu > -1 && ifMenuExist > -1 ) {
                    this.delMenuList.push({
                        privGrantId: node.privGrantId,
                        menuName   : node.menuName
                    })
                }

                if ( ifInitMenu == -1 && ifMenuExist > -1 ) {
                    let delIdx = _.findIndex(this.addMenuList, {
                        privId: node.privId
                    })
                    this.addMenuList.splice(delIdx, 1);
                    let delCheckIdx = _.findIndex(this.checkedGrantList, {
                        privId: node.privId
                    })
                    if ( delCheckIdx != ifInitMenu ) {
                        this.checkedGrantList.splice(delCheckIdx, 1);
                    }
                }
            }
        }
        if ( type == 'com' ) {
            let ifComChecked = (node.hadPriv = !node.hadPriv);
            let ifCompExist = _.indexOf(this.checkedCompList, node.privId);
            if ( ifComChecked ) {
                if ( ifCompExist == -1 ) {
                    this.addCompList.push({
                        privId  : node.privId,
                        compName: node.compName
                    })
                } else {
                    let delIdx = _.findIndex(this.delCompList, {
                        privGrantId: node.privGrantId,
                        compName   : node.compName
                    })
                    this.delCompList.splice(delIdx, 1);
                }
            } else {
                if ( ifCompExist == -1 ) {
                    let delIdx = _.findIndex(this.addCompList, {
                        privId  : node.privId,
                        menuName: node.compName
                    })
                    this.addCompList.splice(delIdx, 1);
                } else {
                    this.delCompList.push({
                        privGrantId: node.privGrantId,
                        compName   : node.compName
                    })
                }
            }
        }
    }

    toggleNode (scope, node, $event) {

        $event.preventDefault();

        this.currentNode = node.menuName;
        this.parMenuId   = node.menuId;

        if ( scope.collapsed ) {
            scope.expand();
            if ( node.hasChildren ) {
                node.loading            = true;
                this.treeData.parMenuId = node.menuId;
                this.service.getTree('menuTree', this.treeData).then((res)=> {
                    node.nodes = res.data;
                    let exist;
                    for (let i = 0, l = res.data.length; i < l; i++) {
                        if ( res.data[ i ].hadPriv == true ) {
                            exist = _.findIndex(this.checkedGrantList, {privId: res.data[ i ].privId});
                            if ( exist == -1 ) {
                                this.checkedGrantList.push({
                                    privId     : res.data[ i ].privId,
                                    privGrantId: res.data[ i ].privGrantId
                                });
                            }
                        }
                    }
                }).finally(function () {
                    node.loading = false;
                });
            }

            if ( node.hadComp == true ) {
                node.loading         = true;
                this.compData.menuId = node.menuId;
                // 请求控件
                this.service.getComp('privGrant', this.compData).then((res)=> {
                    node.compNodes = res.data;
                    for (let i = 0, l = res.data.length; i < l; i++) {
                        if ( res.data[ i ].hadPriv == true ) {
                            this.checkedCompList.push({
                                privId     : res.data[ i ].privId,
                                privGrantId: res.data[ i ].privGrantId
                            });
                        }
                    }
                }).finally(function () {
                    node.loading = false;
                });
            }
        } else {
            scope.collapse();
        }
    }

    collection (list, attr) {
        let r = [];
        angular.forEach(list, function (v) {
            r.push(v[ attr ])
        })
        return r;
    }

    batDelete (src, target, attr) {
        let idx;
        angular.forEach(target, function (v) {
            idx = _.findIndex(src, attr ? {privGrantId: v} : v);
            src.splice(idx, 1)
        })
    }

    save (type) {
        let privMenuAddPris      = this.addMenuList.length && this.collection(this.addMenuList, 'privId'),
            privMenuDelPris      = this.delMenuList.length && this.collection(this.delMenuList, 'privGrantId'),
            privCompAddPris      = this.addCompList.length && this.collection(this.addCompList, 'privId'),
            privCompDelPris      = this.delCompList.length && this.collection(this.delCompList, 'privGrantId');
        this.privMenuAddData.ids = privMenuAddPris && privMenuAddPris.join(',');
        this.privMenuDelData.ids = privMenuDelPris && privMenuDelPris.join(',');
        this.privCompAddData.ids = privCompAddPris && privCompAddPris.join(',');
        this.privCompDelData.ids = privCompDelPris && privCompDelPris.join(',');
        if ( type == 'menu' ) {
            //批量增加菜单
            if ( privMenuAddPris.length ) {
                this.service.insert('batchPriv', this.privMenuAddData).then(()=> {
                    this.addMenuList = [];
                    this.notify.success({
                        'title'  : '提示',
                        'message': '操作成功!'
                    });
                }).catch(function (data) {
                    this.notify.error({
                        'title'  : '提示',
                        'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
                    });
                });
            }

            // 批量删除菜单
            if ( privMenuDelPris.length ) {
                this.service.delItem('batchPriv', this.privMenuDelData).then(()=> {
                    this.delMenuList = [];
                    this.batDelete(this.checkedGrantList, privMenuDelPris, 1);
                    this.notify.success({
                        'title'  : '提示',
                        'message': '操作成功!'
                    });
                }).catch(function (data) {
                    this.notify.error({
                        'title'  : '提示',
                        'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
                    });
                });
            }
        }

        if ( type == 'com' ) {
            // 批量增加组件
            if ( privCompAddPris.length ) {
                this.service.insert('batchPriv', this.privCompAddData).then(()=> {
                    this.addCompList = [];
                    this.notify.success({
                        'title'  : '提示',
                        'message': '操作成功!'
                    });
                }).catch(function (data) {
                    this.notify.error({
                        'title'  : '提示',
                        'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
                    });
                });
            }
            // 批量删除组件
            if ( privCompDelPris.length ) {
                this.service.delItem('batchPriv', this.privCompDelData).then(()=> {
                    this.delCompList = [];
                    this.notify.success({
                        'title'  : '提示',
                        'message': '操作成功!'
                    });
                }).catch(function (data) {
                    this.notify.error({
                        'title'  : '提示',
                        'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
                    });
                });
            }
        }
    }
}

export default Controller;